const { OperationLog } = require('../models')
const logger = require('../utils/logger')
const UserLog = require('../models/userLog')

// 创建操作日志
const createLog = async (logData, transaction) => {
  try {
    const log = await OperationLog.create(logData, { transaction })
    return log
  } catch (error) {
    logger.error('创建日志失败:', error)
    throw error
  }
}

// 获取日志列表
const getLogs = async ({ page = 1, size = 10, type, startTime, endTime }) => {
  try {
    const where = {}
    
    if (type) {
      where.type = type
    }
    
    if (startTime && endTime) {
      where.create_time = {
        [Op.between]: [startTime, endTime]
      }
    }

    const { count, rows } = await OperationLog.findAndCountAll({
      where,
      order: [['create_time', 'DESC']],
      limit: size,
      offset: (page - 1) * size
    })

    return {
      total: count,
      list: rows,
      page,
      size
    }
  } catch (error) {
    logger.error('获取日志列表失败:', error)
    throw error
  }
}

// 删除日志
const deleteLogs = async (ids) => {
  try {
    const result = await OperationLog.destroy({
      where: {
        id: {
          [Op.in]: ids
        }
      }
    })
    return result
  } catch (error) {
    logger.error('删除日志失败:', error)
    throw error
  }
}

class LogService {
  /**
   * 记录用户权限变更日志
   */
  static async logPermissionChange({
    user_id,
    operator_id,
    before,
    after,
    remark,
    ip,
    transaction
  }) {
    try {
      await UserLog.create({
        user_id,
        operator_id,
        type: 'permission',
        content: '权限变更',
        before,
        after,
        ip,
        remark
      }, { transaction })
      
      logger.info('Permission change logged', {
        user_id,
        operator_id,
        type: 'permission',
        before,
        after
      })
    } catch (error) {
      logger.error('Log permission change error:', error)
      throw error
    }
  }

  /**
   * 记录角色变更日志
   */
  static async logRoleChange({
    user_id,
    operator_id,
    before,
    after,
    remark,
    ip,
    transaction
  }) {
    try {
      await UserLog.create({
        user_id,
        operator_id,
        type: 'role',
        content: '角色变更',
        before,
        after,
        ip,
        remark
      }, { transaction })
      
      logger.info('Role change logged', {
        user_id,
        operator_id,
        type: 'role',
        before,
        after
      })
    } catch (error) {
      logger.error('Log role change error:', error)
      throw error
    }
  }

  /**
   * 记录部门变更日志
   */
  static async logDepartmentChange({
    user_id,
    operator_id,
    before,
    after,
    remark,
    ip,
    transaction
  }) {
    try {
      await UserLog.create({
        user_id,
        operator_id,
        type: 'department',
        content: '部门变更',
        before,
        after,
        ip,
        remark
      }, { transaction })
      
      logger.info('Department change logged', {
        user_id,
        operator_id,
        type: 'department',
        before,
        after
      })
    } catch (error) {
      logger.error('Log department change error:', error)
      throw error
    }
  }

  /**
   * 记录部门状态变更日志
   */
  static async logDepartmentStatusChange({
    department_id,
    operator_id,
    before,
    after,
    affected_users,
    remark,
    ip,
    transaction
  }) {
    try {
      // 记录部门状态变更
      await UserLog.create({
        user_id: operator_id,
        operator_id,
        type: 'department_status',
        content: '部门状态变更',
        before: { status: before, department_id },
        after: { status: after, department_id },
        ip,
        remark
      }, { transaction })

      // 记录受影响用户的角色变更
      if (affected_users?.length) {
        for (const user of affected_users) {
          await this.logRoleChange({
            user_id: user.id,
            operator_id,
            before: { role: user.previousRole },
            after: { role: user.currentRole },
            remark: `因部门 ${department_id} 状态变更而自动调整角色`,
            ip,
            transaction
          })
        }
      }
      
      logger.info('Department status change logged', {
        department_id,
        operator_id,
        before,
        after,
        affected_users_count: affected_users?.length
      })
    } catch (error) {
      logger.error('Log department status change error:', error)
      throw error
    }
  }
}

module.exports = {
  createLog,
  getLogs,
  deleteLogs,
  LogService
} 